/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.core.service.util;

import com.alibaba.common.lang.StringUtil;
import com.pingan.mobilegw.core.model.GatewayRequest;
import com.alipay.mobilegw.core.model.constant.HeaderConstant;
import com.pingan.mobilegw.core.model.request.BatchRequestBody;
import com.pingan.mobilegw.core.model.request.SingleRequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 请求工具类
 * 
 * @author jiadao
 * @version $Id: RequestUtil.java, v 0.1 2013-5-14 下午1:54:50 jiadao Exp $
 */
public class RequestUtil {

    /**
     * 将batch请求对象转换为多个single请求对象
     * 
     * @param gatewayRequest
     * @return
     */
    public static List<GatewayRequest> convertBatchToSingle(GatewayRequest gatewayRequest) {

        List<GatewayRequest> requests = new ArrayList<GatewayRequest>();
        BatchRequestBody multiRequestBody = (BatchRequestBody) gatewayRequest.getRequestBody();

        for (SingleRequestBody responseBody : multiRequestBody.getRequestBodies()) {
            GatewayRequest singleRequest = new GatewayRequest();
            singleRequest.setHttpRequest(gatewayRequest.getHttpRequest());
            singleRequest.setHttpResponse(gatewayRequest.getHttpResponse());
            singleRequest.setRequestBody(responseBody);
            singleRequest.setDid(gatewayRequest.getDid());
            singleRequest.setCookies(gatewayRequest.getCookies());
            singleRequest.setHeaders(gatewayRequest.getHeaders());
            singleRequest.setSessionId(gatewayRequest.getSessionId());
            requests.add(singleRequest);
        }

        return requests;

    }

    /**
     * 获取remote_addr
     * 
     * @param request
     * @param headers
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request, Map<String, String> headers) {

        String remoteAddr = StringUtil.equalsIgnoreCase(request.getRemoteAddr(), "127.0.0.1") ? headers
            .get(HeaderConstant.X_FORWARDED_FOR) : request.getRemoteAddr();

        return StringUtil.isNotBlank(remoteAddr) ? remoteAddr : "127.0.0.1";
    }
}
